package com.ysd.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ysd.entity.Admin;


//Filter过滤器
public class LoginFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}
    //doFliter是过滤的核心方法访问所有请求都会先经过该方法，所以只需要在该方法中判断用户有没有登陆过即可
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req=(HttpServletRequest)request;
		HttpServletResponse res=(HttpServletResponse)response;
		
		HttpSession session=req.getSession();
		Admin admin=(Admin)session.getAttribute("admin");
		
		String url=req.getRequestURI();//获得访问的路径
		if(url.endsWith(".css")||url.endsWith(".js")||url.endsWith(".jpg")) {//如果访问静态资源也放行
			chain.doFilter(req, res);//放行
		}else if(url.indexOf("login.html")>0) {//代表访问登录页面
			chain.doFilter(req, res);//放行
		}else {//代表访问的不是登录页面
			if(admin!=null) {//登陆过
				chain.doFilter(req, res);//放行
			}else {//没登陆过
				res.sendRedirect("/huaduoyoupin/admin/login.html");
			}
		}
		
		
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}
